﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using SdmxMl.Common;
using SdmxMl.Helper;
using SdmxMl.Manager;
using SdmxMl.Multiplexor;

namespace PluginMeb
{
    public class DirInfoHelper
    {
        private DataTable tbInfo;

        public DirInfoHelper(ArtefactRefTyped art)
        {

            DataSet ds = Mux.Instance.DirInfo(art.Type.ToString(), art.AgencyId);
            if (ds != null && ds.Tables.Count > 0)
                tbInfo = ds.Tables[0];
            else
                throw new ApplicationException("Unable to access registry");
        }


        public DateTime GetLastUpdateDate(string artefactFullId)
        {
            DateTime dt = DateTime.MaxValue;
            ArtefactRefBase aRef = new ArtefactRefBase(artefactFullId);
            foreach (DataRow row in tbInfo.Rows)
            {
                if (row["ID"].ToString() == aRef.Id && row["AI"].ToString() == aRef.AgencyId && row["VER"].ToString() == aRef.Version)
                {
                    dt = Convert.ToDateTime(row["LU"].ToString());
                    break;
                }
            }
            if (dt == DateTime.MaxValue)
                throw new ApplicationException("Unable to get artefact. " + artefactFullId);

            return dt;
        }

        public bool IsReserved(string artefactFullId)
        {
            bool reserved = false;
            bool found = false;
            ArtefactRefBase aRef = new ArtefactRefBase(artefactFullId);
            foreach (DataRow row in tbInfo.Rows)
            {
                if (row["ID"].ToString() == aRef.Id && row["AI"].ToString() == aRef.AgencyId && row["VER"].ToString() == aRef.Version)
                {
                    reserved = row["CA"].ToString().Length > 0;
                    found = true;
                    break;
                }
            }

            if (found == false)
                throw new ApplicationException("Unable to get artefact. " + artefactFullId);

            return reserved;
        }
    }
}
